<template>
    <div class="common-layout" style="margin-top:0% ;width: 100%; height: 100%; background-color: rgb(233, 233, 233);">
        <el-container style="height: 100%;">
            <el-aside width="75%" style="height:100%;margin-top:1%;margin-right:1% ;margin-left: 1%;">
                <el-header
                    style="line-height:50px;height: 50px; background-color: rgb(247, 244, 244); border: 1px solid gainsboro;">
                    会诊信息
                </el-header>
                <el-header style="height: 100%; background-color: rgb(255, 255, 255); border: 1px solid gainsboro;">
                    <table style="width: 100%; line-height: 60px;color: rgb(83, 82, 82);">
                        <tr>
                            <tb style="width:50%;float: left;">原病理号：{{ detail.detail.case_no }} </tb>
                            <tb style="width:50%;float: right;">送检日期：{{ detail.detail.send_date }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">患者姓名：{{ detail.detail.name }}</tb>
                            <tb style="width:50%;float: right;">送检医院：{{ detail.detail.send_hospital }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">性别：{{ detail.detail.sex }}</tb>
                            <tb style="width:50%;float: right;">送检科室：{{ detail.detail.send_depart }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">年龄：{{ detail.detail.age }}</tb>
                            <tb style="width:50%;float: right;">送检医生：{{ detail.detail.send_doctor }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">民族：{{ detail.detail.nation }}</tb>
                            <tb style="width:50%;float: right;">检查号：{{ detail.detail.no }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">身份证号：{{ detail.detail.idcard }}</tb>
                            <tb style="width:50%;float: right;">住院号：{{ detail.detail.inpatient_no }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">患者手机：{{ detail.detail.mobile }}</tb>
                            <tb style="width:50%;float: right;">病区号：{{ detail.detail.area_no }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">病理分类：{{ detail.detail.pathology_type }}</tb>
                            <tb style="width:50%;float: right;">床号：{{ detail.detail.bed_no }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">取材部位：{{ detail.detail.specimen }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">临床资料：{{ detail.detail.clinical_record }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">病史信息：{{ detail.detail.medical_history }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">手术所见：{{ detail.detail.operation_descript }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">临床诊断：{{ detail.detail.clinical_diagnosis }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">大体所见：{{ detail.detail.gross_descript }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">
                                大体图像：
                                <div class="demo-image__preview">
                                    <el-image style="width: 100px; height: 100px" :src="detail.detail.gross_image"
                                        :zoom-rate="1.2" fit="cover" />
                                </div>
                                <el-image>
                                    <template #error>
                                        <div class="image-slot">
                                            <el-icon><icon-picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">免疫组化：{{ detail.detail.ihc }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">初诊意见：{{ detail.detail.first_diagnosis }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">备注信息：{{ detail.detail.remarks }}</tb>
                        </tr>
                        <tr>
                            <tb style="width:50%;float: left;">
                                附件/影像资料：
                                <div class="demo-image__preview">
                                    <el-image style="width: 100px; height: 100px" :src="detail.detail.content"
                                        :zoom-rate="1.2" fit="cover" />
                                </div>
                                <el-image>
                                    <template #error>
                                        <div class="image-slot">
                                            <el-icon><icon-picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </tb>
                        </tr>
                    </table>
                </el-header>
    
                <el-footer
                    style="margin-top:3%;line-height:50px;height: 50px; background-color: rgb(247, 244, 244); border: 1px solid gainsboro;">
                    病理诊断 （请在下面填写诊断结果）
                </el-footer>
                <el-header
                    style="padding-top: 4%;padding-bottom: 10%; width: 100%;height: 100%; background-color: rgb(255, 255, 255);border: 1px solid gainsboro;">
                    <el-container direction="vertical" style="height: 100%;">
                        <el-header style="margin-top: -2%;">
                            <span style="color: red;">* </span>上传病理图片
                        </el-header>
                        <!-- <el-header style="margin-top: 2%;">
                                <el-upload class="upload-demo" drag
                                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple
                                    style="width: 100%;">
                                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                    <div class="el-upload__text">
                                        <span
                                            style="color: rgb(189, 185, 185);">您可以使用QQ、微信等截屏工具，截图后点击虚线框内粘贴，或者点击添加图片按钮，来上传图片</span>
                                    </div>
                                </el-upload>
                            </el-header> -->
    
                        <!-- <el-header style="margin-top: 130px;">
                                <el-divider />
                            </el-header> -->
    
                        <el-header style="margin-top:0%;width: 100%; margin-bottom: 9%;">
                            <div class="component-upload-image" style="width: 100%;">
                                <el-upload multiple :action="uploadImgUrl" list-type="picture-card"
                                    :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" :limit="limit"
                                    :on-error="handleUploadError" :on-exceed="handleExceed" ref="imageUpload"
                                    :before-remove="handleDelete" :show-file-list="true" :headers="headers"
                                    :file-list="fileList" :on-preview="handlePictureCardPreview"
                                    :class="{ hide: fileList.length >= limit }" style="width: 100%;" :auto-upload="false">
                                    <!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            <span style="color: rgb(189, 185, 185);">
              您可以使用QQ、微信等截屏工具，截图后点击虚线框内粘贴，或者点击添加图片按钮，来上传图片
            </span>
          </div> -->
                                    <el-icon class="avatar-uploader-icon">
                                        <plus />
                                    </el-icon>
                                </el-upload>
                                <!-- 上传提示 -->
                                <div class="el-upload__tip" v-if="showTip">
                                    请上传
                                    <template v-if="fileSize">
                                        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
                                    </template>
                                    <template v-if="fileType">
                                        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
                                    </template>
                                    的文件
                                </div>
    
                                <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
                                    <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
                                </el-dialog>
                            </div>
                        </el-header>
    
                        <el-header style="margin-top: 20px;">
                            <span style="color: red;">* </span>诊断意见
                        </el-header>
    
                        <el-header>
                            <el-input type="textarea" v-model="form.expert_diagnosis" />
                        </el-header>
    
                        <el-header>
                            <el-row class="mb-4" v-if='status == 2'>
                                <el-button type="success" @click="save(1)">保存草稿</el-button>
                                <el-button type="primary" @click="save(2)">提交</el-button>
                                <el-button @click="getBack()">返回</el-button>
                            </el-row>
                        </el-header>
                    </el-container>
                </el-header>
    
            </el-aside>
            <el-main style="margin-right:1.5%;margin-top:0%;height: 100%;line-height: 55px;">
                <el-header
                    style="height: 100%; width: 100%; background-color: rgb(247, 244, 244); border: 1px solid gainsboro;">
                    会诊报告
                </el-header>
                <el-header style=" width: 100%; background-color: rgb(255, 255, 255);border: 1px solid gainsboro;">
                    未出
                </el-header>
                <br>
                <el-header
                    style="height: 50px; width: 100%; background-color: rgb(247, 244, 244); border: 1px solid gainsboro;">
                    会诊流程
                </el-header>
                <el-header style=" width: 100%; background-color: rgb(255, 255, 255);border: 1px solid gainsboro;">
                    未出
                </el-header>
                <br>
                <el-header
                    style="height: 50px; width: 100%; background-color: rgb(247, 244, 244); border: 1px solid gainsboro;">
                    会诊留言
                </el-header>
                <el-header style=" width: 100%; background-color: rgb(255, 255, 255);border: 1px solid gainsboro;">
                    未出
                </el-header>
                <br>
    
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
	import { findOne, upbyid, upstatus } from "@/api/clinic/details";
	import { UploadFilled } from '@element-plus/icons-vue'
	import { getCurrentInstance, nextTick, reactive, watch } from "vue";
	//上传文件
	import { download } from '@/utils/request'
	import fileUpload from '@/components/FileUpload/uploadTu'

	const { proxy } = getCurrentInstance();
	const route = useRouter();

	//会诊病例 传过来的数据
	const status = localStorage.getItem('emrCaseStatus');
	console.log("details:" + status);

	// 表单数据
	const form = reactive({
		id: localStorage.getItem('emrCaseId'),
		expert_diagnosis: '',
		gross_image: ''
	})

	//初始化页面数据
	//病例详情数据
	let detail = reactive({
		detail: {}
	});

	function emrcasebyid() {
		findOne(form.id).then(res => {
			console.log("病例详情的值" + JSON.stringify(res.data[0]));
			detail.detail = res.data[0]
			form.expert_diagnosis = detail.detail.expert_diagnosis;
			if (detail.detail.pathology_type == 1) {
				detail.detail.pathology_type = "常规"
			} else if (detail.detail.pathology_type == 2) {
				detail.detail.pathology_type = "冰冻"
			} else if (detail.detail.pathology_type == 3) {
				detail.detail.pathology_type = "细胞"
			} else if (detail.detail.pathology_type == 4) {
				detail.detail.pathology_type = "组织"
			} else {
				detail.detail.pathology_type = "其他"
			}
			if (detail.detail.sex == 1) {
				detail.detail.sex = "男";
			} else if (detail.detail.sex == 2) {
				detail.detail.sex = "女";
			}
		}).catch(error => {
			console.error(error);
		})
	}
	emrcasebyid();
	console.log("detail对象：" + JSON.stringify(detail.detail));

	// watch(detail,(old,yang)=>{
	//     console.log(old+"+"+yang);
	// })


	console.log()

	//诊断意见

	const upfrom = reactive({
		id: form.id,
		status: status
	})
	//按钮 保存 1 提交 2
	async function save(status) {
		// 上传图片
		await proxy.$refs["imageUpload"].submit();

		// 上传数据
		setTimeout(() => {
			upbyid(form).then(res => {
				console.log("保存：" + form.gross_image + "/" + form.expert_diagnosis);
				console.log("======" + JSON.stringify(res))
			}).catch(error => {
				console.error(error);
			})

			upstatus(upfrom).then(res => {
				console.log("2 n成功");
				document.location.reload();
			}).catch(error => {
				console.log("2 n失败");
				console.error(error);
			})
		}, 1000)

	}
	//返回按钮
	const getBack = () => {
		window.location.href = "http://localhost:8888/consultation/clinic";
	}

	const tableData = [
		{
			date: '2016-05-03',
			name: 'Tom',
			address: 'No. 189, Grove St, Los Angeles',
		}
	]

	//图像
	// const content = reactive('');


	import { getToken } from "@/utils/auth";

	const props = defineProps({
		modelValue: [String, Object, Array],
		// 图片数量限制
		limit: {
			type: Number,
			default: 1,
		},
		// 大小限制(MB)
		fileSize: {
			type: Number,
			default: 5,
		},
		// 文件类型, 例如['png', 'jpg', 'jpeg']
		fileType: {
			type: Array,
			default: () => ["png", "jpg", "jpeg"],
		},
		// 是否显示提示
		isShowTip: {
			type: Boolean,
			default: true
		},
	});

	const emit = defineEmits();
	const number = ref(0);
	const uploadList = ref([]);
	const dialogImageUrl = ref("");
	const dialogVisible = ref(false);
	const baseUrl = import.meta.env.VITE_APP_BASE_API;
	const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传的图片服务器地址
	const headers = ref({ Authorization: "Bearer " + getToken() });
	const fileList = ref([]);
	const showTip = computed(
		() => props.isShowTip && (props.fileType || props.fileSize)
	);

	watch(() => props.modelValue, val => {
		if (val) {
			// 首先将值转为数组
			const list = Array.isArray(val) ? val : props.modelValue.split(",");
			// 然后将数组转为对象数组
			fileList.value = list.map(item => {
				if (typeof item === "string") {
					/*if (item.indexOf(baseUrl) === -1) {
					  item = { name: baseUrl + item, url: baseUrl + item };
					} else {
					  item = { name: item, url: item };
					}*/
					item = { name: item, url: item };
				}
				return item;
			});
		} else {
			fileList.value = [];
			return [];
		}
	}, { deep: true, immediate: true });

	// 上传前loading加载
	function handleBeforeUpload(file) {
		let isImg = false;
		if (props.fileType.length) {
			let fileExtension = "";
			if (file.name.lastIndexOf(".") > -1) {
				fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
			}
			isImg = props.fileType.some(type => {
				if (file.type.indexOf(type) > -1) return true;
				if (fileExtension && fileExtension.indexOf(type) > -1) return true;
				return false;
			});
		} else {
			isImg = file.type.indexOf("image") > -1;
		}
		if (!isImg) {
			proxy.$modal.msgError(
				`文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
			);
			return false;
		}
		if (props.fileSize) {
			const isLt = file.size / 1024 / 1024 < props.fileSize;
			if (!isLt) {
				proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
				return false;
			}
		}
		proxy.$modal.loading("正在上传图片，请稍候...");
		number.value++;
	}

	// 文件个数超出
	function handleExceed() {
		proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
	}

	// 上传成功回调
	function handleUploadSuccess(res, file) {
		if (res.code === 200) {
			uploadList.value.push({ name: res.fileName, url: res.url });
			form.gross_image = res.url;
			console.log(form.gross_image);
			uploadedSuccessfully();
		} else {
			number.value--;
			proxy.$modal.closeLoading();
			proxy.$modal.msgError(res.msg);
			proxy.$refs.imageUpload.handleRemove(file);
			uploadedSuccessfully();
		}
	}

	// 删除图片
	function handleDelete(file) {
		const findex = fileList.value.map(f => f.name).indexOf(file.name);
		if (findex > -1 && uploadList.value.length === number.value) {
			fileList.value.splice(findex, 1);
			emit("update:modelValue", listToString(fileList.value));
			return false;
		}
	}

	// 上传结束处理
	function uploadedSuccessfully() {
		if (number.value > 0 && uploadList.value.length === number.value) {
			fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
			uploadList.value = [];
			number.value = 0;
			emit("update:modelValue", listToString(fileList.value));
			proxy.$modal.closeLoading();
		}
	}

	// 上传失败
	function handleUploadError() {
		proxy.$modal.msgError("上传图片失败");
		proxy.$modal.closeLoading();
	}

	// 预览
	function handlePictureCardPreview(file) {
		dialogImageUrl.value = file.url;
		dialogVisible.value = true;
	}

	// 对象转成指定字符串分隔
	function listToString(list, separator) {
		let strs = "";
		separator = separator || ",";
		for (let i in list) {
			if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
				strs += list[i].url.replace(baseUrl, "") + separator;
			}
		}
		return strs != "" ? strs.substr(0, strs.length - 1) : "";
	}

</script>

<style>
.demo-image__error .image-slot {
    font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
    font-size: 30px;
}

.demo-image__error .el-image {
    width: 100%;
    height: 200px;
}
</style>